package com.cloudinnov.controller.api;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.model.RealTime;
import com.cloudinnov.utils.CommonUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.exceptions.JedisException;

/**
 * @author chengning
 * @date 2016年2月26日下午2:32:50
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Controller
@RequestMapping("/receiveData")
public class ReceiveDataController extends BaseController {
    static final Logger _LOG = LoggerFactory.getLogger(ReceiveDataController.class);
    private SimpleDateFormat sdf = new SimpleDateFormat(":yyyyMMddHH");
    private static final String SPLITTER_LEVEL0 = ",";
    private static final String SPLITTER_LEVEL1 = ";";
    private static final String KEY_NAME = "point:";
    private static final String VALUE_NAME = ":value";
    private static final Integer RECENT_LIST_COUNT = 1000;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private AmqpTemplate faultTemplate;
    @Autowired
    private AmqpTemplate realTimeTemplate;

    @RequestMapping(value = "/putRealtime", method = RequestMethod.POST)
    public void realTime(String data, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Jedis redis = null;
        StringBuilder sbRedis;
        try {
            redis = jedisPool.getResource();
            Pipeline pipeline = redis.pipelined();
            // 处理数据
            List<RealTime> jsonArray = JSON.parseArray(data, RealTime.class);
            
            _LOG.debug("发送数据大小为:\t" + 1);
            String keyRealtime, value;
            if (jsonArray != null && jsonArray.size() > 0) {
                _LOG.debug("接收数据大小为:\t" + jsonArray.size());
                sbRedis = new StringBuilder();
                String ts = String.valueOf(System.currentTimeMillis() / 1000);
                sbRedis.append(ts + SPLITTER_LEVEL0);
                for (RealTime rt : jsonArray) {
                    _LOG.debug("Key:\t" + rt.getCode() + "\tValue:\t" + rt.getValue());
                    sbRedis.append(rt.getCode() + SPLITTER_LEVEL1 + rt.getValue() + SPLITTER_LEVEL1);
                    keyRealtime = KEY_NAME + rt.getCode() + VALUE_NAME;
                    value = ts + SPLITTER_LEVEL0 + rt.getValue();
                    pipeline.lpush(keyRealtime, value);
                    pipeline.ltrim(keyRealtime, 0, RECENT_LIST_COUNT);
                }
                pipeline.sync();
                realTimeTemplate.convertAndSend(sbRedis.toString());
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                 map.put("data", "receive realData is Empty!");
                String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
                response.getWriter().print(returnData);
            }
        } catch (JedisException e) {
            _LOG.error("realTime is error,", e);
        } finally {
            jedisPool.returnResource(redis);
        }
    }
    
    
    @RequestMapping("/putFault")
    @ResponseBody
    public void putFault(String data, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 处理数据
        Map<String, Object> map = new HashMap<String, Object>();
        List<RealTime> jsonArray = JSON.parseArray(data, RealTime.class);
        if (jsonArray != null && jsonArray.size() > 0) {
            Jedis redisClient = null;
            try {
                redisClient = jedisPool.getResource();
                redisClient.select(CommonUtils.REDIS_FAULT_VALUEDB);
                for (RealTime rt : jsonArray) {
                    int faultValue = (int) Float.parseFloat(rt.getValue());
                    _LOG.debug("FaultChannelCode:\t" + rt.getCode() + "\tFaultCode:\t" + rt.getValue());
                    StringBuffer sb = new StringBuffer();
                    String redisCode = redisClient.hget(rt.getCode(), faultValue + "");
                    if (redisCode == null) {
                        sb.append(rt.getCode()).append(",").append(faultValue + "");
                        redisClient.hset(rt.getCode() + "", faultValue + "", "1");
                        redisClient.hset(rt.getCode() + "", faultValue + "" + ":total", "1");
                        faultTemplate.convertAndSend(sb.toString());
                    } else {
                        redisClient.hincrBy(rt.getCode(), faultValue + "" + ":total", 1);
                    }
                }
            } catch (Exception e) {
                _LOG.error("[method]:putFault:\t" + e);
            } finally {
                jedisPool.returnResource(redisClient);
            }
        } else {
            map.put("data", "receive faultData is Empty!");
            String returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
            response.getWriter().print(returnData);
        }
    }
}
